package cn.minhx.infrastructure.gateway;

import cn.minhx.types.enums.ResponseCode;
import cn.minhx.types.exception.AppException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;

/**
 * 拼团回调服务
 *
 * @author min
 */
@Slf4j
@Service
public class GroupBuyNotifyService {

	@Resource
	private OkHttpClient okHttpClient;

	public String groupBuyNotify(String apiUrl, String notifyRequestDTOJSON) throws Exception {
		try {
			// 1. 构建参数
			MediaType mediaType = MediaType.parse("application/json");
			RequestBody body = RequestBody.create(notifyRequestDTOJSON, mediaType);
			Request request = new Request.Builder().url(apiUrl).post(body).addHeader("content-type", "application/json")
					.build();

			// 2. 调用接口
			try (Response response = okHttpClient.newCall(request).execute()) {
				// 3. 返回结果
				assert response.body() != null;
				return response.body().string();
			}
		} catch (Exception e) {
			log.error("拼团回调 HTTP 接口服务异常 {}", apiUrl, e);
			throw new AppException(ResponseCode.HTTP_EXCEPTION);
		}
	}

}
